<?php

	require_once(dirname(__FILE__)."/../core/safeParam.php");

	class menu
	{
		function checkAdminPassword($username, $password){
			global $database;
    		$hashedPassword = md5($password);
    		$results = $database->select("select username from config where username = '$username' and password = '$hashedPassword'");
    		
    		if (!$results) {
    			return false;
    		} else {
    			return $results[0]['username'];
    		} 
  		}

  		function changeCats($vars){
    		global $database;
    		$items = $vars['items'];
    		
    		foreach ($items as $key => $value) {
      		$update['cat'] = $vars['cat'];
      		$database->update_array("menu_item", $update, "id=$value");
      		header('location: ../admin/index.php?edit=menu&cat_id=' . $vars['cat'] . '&function=edit-cat&update=1');
    		} //$items as $key => $value
  		}

  		function editGateway($vars){
    		global $database;
    		$input['gateway'] = $vars['gateway'];
    		$query            = $database->update_array('config', $input, "id=" . $vars['rid'] . "");
    		header('location: ../admin/index.php?edit=gateway&updated=1');
  		}

  		function editConfigVars($vars, $files){
    		global $database;
    		$database->update_array('config', $vars, "id=" . $vars['id'] . "");
    		header('location: ../admin/index.php?edit=config&updated=1');
  		}


  		function editConfig($vars, $files){
    		global $database;
    		
    		$opentime       = serialize($vars['open']);
    		$closetime      = serialize($vars['close']);
    		$blackout_start = serialize($vars['blackout_start']);
    		$blackout_end   = serialize($vars['blackout_end']);
    		
    		$vars['hours']  = '' . $opentime . '+' . $closetime . '+' . $blackout_start . '+' . $blackout_end . '';
    		
    		unset($vars['open']);
    		unset($vars['close']);
    		unset($vars['blackout_start']);
    		unset($vars['blackout_end']);
    
    		$checkout_fields = serialize($vars['checkout_fields']);
    		unset($vars['checkout_fields']);
    		
    		$vars['checkout_fields'] = $checkout_fields;
    		
    		$deliverytime = $vars['deliverytime'];
    		    		
    		if ($files['image']['size'] != 0) {
    			$image        = uploadImage($files, '1200', '1200', '../UserFiles/Image/product_photos/', 'image');
    			$vars['logo'] = $image;
    		}
    		
    		if ($files['fondo']['size'] != 0){
    			$fondo = uploadImage($files, '1200', '1200', '../UserFiles/Image/product_photos/', 'fondo');
    			$vars['delivery_minimum'] = $fondo;
    		}
    		
    		if($vars['resetfondo'] == 2){
    			$vars['delivery_minimum'] = '1';
    		}
    		unset($vars['resetfondo']);
    		
    		$siteNameAux = str_replace(" ", "_", $vars['sitename']);
    		$vars['sitename'] = $siteNameAux;
    		
    		$smtpPortAux = $vars['smtp_port'];
    		$smtpPortAux = "54" . $smtpPortAux;
    		$vars['smtp_port'] = $smtpPortAux;

    		$error = "";
    		$_SESSION['error'] = "";
    		
    		if ($vars['password'] != ""){
    			//only save password if the user supplied a new one. We no longer 'display' the current password.
      		$userid = $this->checkAdminPassword($vars['username'], $vars['current_password']); 
      		if (! $userid){
        			$error .= "Cotraseña actual NO válida.<br/>"; // $lang['reg_incorrect_password'];
      		}

      		if (trim($vars['password']) == ""){
        			$error .= "Contraseña no puede quedar en blanco.<br/>";
      		} 

      		if ($vars['password'] != $vars['password_confirm']){
        			$error .= "Nueva Contraseña no es igual a Confirmar Contraseña.<br/>"; // $lang['reg_passwords_not_match'];
      		}
     
      		if (!$error){
        			$vars['password']  = md5($vars['password']);
      		} else {
        			unset($vars['password']);
      		}
			} else {
      		unset($vars['password']);
    		}

    		// don't save these fields, update query will fail...
    		unset($vars['password_confirm']);
    		unset($vars['current_password']);

    		$rid = $vars['id'];

    		if ($error){
      		$_SESSION['error'] = $error;
      		header("location: ../admin/index.php?edit=config&rid=$rid&updated=0");
      		exit();
    		} 

    		$query = $database->update_array('config', $vars, "id=". $vars['id'] ."");
    
    		if (!$query){
      		$error .= "Error al actualizar Configuración: ".mysql_error();
      		$_SESSION['error'] = $error;
      		header("location: ../admin/index.php?edit=config&rid=$rid&updated=0");
      		exit();
    		}

    		unset($_SESSION['error']);
    		header('location: ../admin/index.php?edit=config&updated=1');
  		}


  		function deleteConfig($id){
    		global $database;
    		
    		$query = $database->delete("config", "id = '$id'");
    		$query = $database->delete("rating", "rid = '$id'");
    		$query = $database->delete("locations", "rid = '$id'");
    		
    		//ITEMS
    		$results = $database->select("SELECT * FROM menu_item  where rid = " . $id . " ");
			if($results){
				for ($i = 0; $i < count($results); $i++) {
      			$database->delete("menu_item", "id = " . $results[$i]['id'] . "");
    			}
			}    		

    		
    		//PEDIDOS
    		$results = $database->select("SELECT * FROM order_sum  where rid = " . $id . " ");
			if($results){
			    for ($i = 0; $i < count($results); $i++) {
      			$database->delete("order_sum", "id = " . $results[$i]['id'] . "");
    			}
			}
    		
    		//NOTICIAS
    		$results = $database->select("SELECT * FROM news  where rid = " . $id . " ");
			if($results){
				for ($i = 0; $i < count($results); $i++) {
      			$database->delete("news", "id = " . $results[$i]['id'] . "");
    			}
			}
			
			//OPCIONES
			$results = $database->select("SELECT * FROM options  where rid = " . $id . " ");    		  		
    		if($results){
				for ($i = 0; $i < count($results); $i++) {
      			$database->delete("options", "id = " . $results[$i]['id'] . "");
    			}
			}
			
    		header('location: ../admin/index.php?edit=config&updated=1');
  		}


  		function addConfig($vars, $files) {  			
    		global $database;
    		unset($vars['id']);
    		
    		$opentime       = serialize($vars['open']);
    		$closetime      = serialize($vars['close']);
    		$blackout_start = serialize($vars['blackout_start']);
    		$blackout_end   = serialize($vars['blackout_end']);
    		
    		$vars['hours']  = '' . $opentime . '+' . $closetime . '+' . $blackout_start . '+' . $blackout_end . '';
    		
    		unset($vars['open']);
    		unset($vars['close']);
    		unset($vars['blackout_start']);
    		unset($vars['blackout_end']);
    		
    		$checkout_fields = serialize($vars['checkout_fields']);
    		unset($vars['checkout_fields']);
    		
    		$vars['checkout_fields'] = $checkout_fields;
    		
    		if ($files['image']['size'] != 0) {
      		$image        = uploadImage($files, '1200', '1200', '../UserFiles/Image/product_photos/', 'image');
      		$vars['logo'] = $image;
    		}
    		
    		unset($vars['resetfondo']);
    		
    		$siteNameAux = str_replace(" ", "_", $vars['sitename']);
    		$vars['sitename'] = $siteNameAux;
    		
    		$smtpPortAux = $vars['smtp_port'];
    		$smtpPortAux = "54" . $smtpPortAux;
    		$vars['smtp_port'] = $smtpPortAux;
    		
    		/*	 Inserto registro en la tabla config		*/
    		$query = $database->insert_array('config', $vars);
			
  			/*	Inserto registro en la tabla options		*/
  			$check_areas = $database->select("SELECT * FROM config WHERE sitename='". $siteNameAux ."'");
  			$options['name']	= "cb-global-sitedocs";
			$options['value']	= 0;
			$options['rid']	= $check_areas[0]['id'];  
  			$query = $database->insert_array('options', $options);
  			
    		$localId = $check_areas[0]['id'];
    		$rating['uid'] 	= 0;
    		$rating['rid'] 	= $localId;
    		$rating['level']	= 0;
    		$rating['votos']	= 0;
    		$database->insert_array('rating', $rating);
    		
    		header('location: ../admin/index.php?edit=config&updated=1');
  		}


  		function editHome($vars){
    		global $database;
    		$vars_insert['home'] = $vars['home'];
    		error_log("insert home: ".$vars_insert['home']);
    		$query               = $database->update_array('config', $vars_insert, "id=" . $vars['id'] . "");
    		header('location: ../admin/index.php?edit=home&updated=1');
  		}


  		function pizzaAdd($vars){
    		global $database;
    		$name          = $vars['name'];
    		$size          = $vars['size'];
    		$price         = $vars['price'];
    		$topping_price = $vars['topping_price'];
    		$toppings      = $vars['toppings'];
    		$base          = $vars['base'];
    		$max_toppings  = $vars['max_toppings'];
    		$half          = $vars['half'];
    		$tier_amount   = $vars['tier_amount'];
    		$tier_price    = $vars['tier_price'];
    		$discount      = $vars['discount'];
    		$free_topping  = $vars['free_topping'];
    		$meat_toppings = $vars['meat_toppings'];
    		$topoff        = $vars['topoff'];
    		$sauce         = $vars['sauce'];
    		
    		if ($vars['sides'][0] == "") {
      		$sides[0] = 0;
    		} //$vars['sides'][0] == ""
    		else {
      		$sides[0] = 1;
    		}
    		
    		if ($vars['sides'][1] == "") {
		      $sides[1] = 0;
    		} //$vars['sides'][1] == ""
    		else {
      		$sides[1] = 1;
    		}
    		
    		if ($vars['sides'][2] == "") {
      		$sides[2] = 0;
    		} //$vars['sides'][2] == ""
    		else {
      		$sides[2] = 1;
    		}
    		
    		if ($vars['sides'][3] == "") {
      		$sides[3] = 0;
    		} //$vars['sides'][3] == ""
    		else {
      		$sides[3] = 1;
    		}
    		
    		$sides = serialize($sides);
    		$rid   = $vars['rid'];
    		$query = $database->insert("pizza", "name,size,price,topping_price,toppings,rid,base,max_toppings,half,tier_amount,tier_price,discount,meat_toppings,topoff,sides,free_topping,sauce", "'$name', '$size', '$price', '$topping_price', '$toppings', '$rid', '$base', '$max_toppings', '$half', '$tier_amount', '$tier_price', '$discount', '$meat_toppings', '$topoff', '$sides', '$free_topping','$sauce'");
    		header('location: ../admin/index.php?edit=pizza&updated=1');
  		}

  		function pizzaEdit($vars){
    		global $database;
    		$id            = $vars['id'];
    		$name          = $vars['name'];
    		$size          = $vars['size'];
    		$price         = $vars['price'];
    		$topping_price = $vars['topping_price'];
    		$toppings      = $vars['toppings'];
    		$base          = $vars['base'];
    		$max_toppings  = $vars['max_toppings'];
    		$half          = $vars['half'];
    		$tier_amount   = $vars['tier_amount'];
    		$tier_price    = $vars['tier_price'];
    		$discount      = $vars['discount'];
    		$free_topping  = $vars['free_topping'];
    		$meat_toppings = $vars['meat_toppings'];
    		$topoff        = $vars['topoff'];
    		$sauce         = $vars['sauce'];
    		
    		if ($vars['sides'][0] == "") {
      		$sides[0] = 0;
    		} //$vars['sides'][0] == ""
    		else {
      		$sides[0] = 1;
    		}
    		
    		if ($vars['sides'][1] == "") {
      		$sides[1] = 0;
    		} //$vars['sides'][1] == ""
    		else {
      		$sides[1] = 1;
    		}
    		
    		if ($vars['sides'][2] == "") {
      		$sides[2] = 0;
    		} //$vars['sides'][2] == ""
    		else {
      		$sides[2] = 1;
    		}
    		
    		if ($vars['sides'][3] == "") {
      		$sides[3] = 0;
    		} //$vars['sides'][3] == ""
    		else {
      		$sides[3] = 1;
    		}
    		
    		$sides = serialize($sides);
    		$query = $database->update("pizza", "name = '$name' , price = '$price', size = '$size', topping_price = '$topping_price', toppings = '$toppings', base = '$base', max_toppings = '$max_toppings', half = '$half' , tier_amount = '$tier_amount' , tier_price = '$tier_price',discount = '$discount',meat_toppings='$meat_toppings',topoff= '$topoff',sides =  '$sides',free_topping =  '$free_topping',sauce = '$sauce'", "id = '$id'");
    		header('location: ../admin/index.php?edit=pizza&updated=1');
  		}

  		function pizzaDelete($vars){
    		global $database;
    		$id    = $vars['id'];
    		$query = $database->delete("pizza", "id = '$id'");
    		header('location: ../admin/index.php?edit=pizza&updated=1');
  		}

  		function toppingAdd($vars){
    		global $database;
    		$name  = $vars['name'];
    		$price = $vars['price'];
    		$query = $database->insert("pizza_toppings", "name, price", "'$name', '$price'");
    		header('location: ../admin/index.php?page=menus&updated=1');
  		}

  		function menusAdd($vars){
    		global $database;
    		$name  = $vars['name'];
    		$type  = $vars['type'];
    		$price = $vars['price'];
    		$query = $database->insert("menu", "name, type,price", "'$name', '$type', '$price'");
    		header('location: ../admin/index.php?page=menus&updated=1');
  		}

  		function menusModify($vars){
    		global $database;
    		$mid         = $vars['mid'];
    		$id          = $vars['id'];
    		$name        = $vars['name'];
    		$type        = $vars['type'];
    		$price       = $vars['price'];
    		$description = $vars['description'];
    		$query       = $database->update("menu_cat", "name = '$name' , price = '$price', description = '$description'", "id = '$id'");
    		header('location: ../admin/index.php?updated=1&cat_id=' . $mid . '&edit=menu');
  		}

  		function menusDelete($id){
    		global $database;
    		
    		$query = $database->delete("menu", "id = '$id'");
    		header('location: ../admin/index.php?edit=menu&updated=1');
  		}

  		function menusCategoryAdd($vars, $files){
    		global $database;
    		
    		$cat['rid'] = $vars['rid'];
    		    		
    		if($vars['check'] == true){
    			$cat['name'] = $vars['name'];
    			$cat['description'] = 1;	
    			
    			if ($files['imagenPre']['size'] != 0) {
    				$image = uploadImage($files, '500', '100', '../UserFiles/Image/product_photos/', 'imagenPre');
      			$cat['imagenPre'] = $image;
    			}
    			
    		} else {
    			$cat['name'] = $vars['namecat'];
    			$cat['description'] = 0;
    		}
    		    		
    		$cat['price']= serialize($vars['price']);

    		$database->insert_array("menu_cat", $cat);
    		header('location: ../admin/index.php?edit=menu&updated=1');
  		}
  
  		// ==================================================================
  		// We would like to modify the menu category

  		function menusCategoryModify($vars, $files){
    		global $database;
    		
    		$id = $vars['id'];
    		$cat['rid'] = $vars['rid'];
    		$cat['name'] = $vars['name'];
    		
    		if ($files['imagenPre']['size'] != 0) {
    				$image = uploadImage($files, '500', '100', '../UserFiles/Image/product_photos/', 'imagenPre');
      			$cat['imagenPre'] = $image;
    		}
    		 		    		
    		$database->update_array("menu_cat", $cat, "id='$id'");
    		header('location: ../admin/index.php?edit=menu&updated=1');
  		}

  		function orderCats($vars){
    		global $database;
    		$posid       = $vars['posid'];
    		$pos         = $vars['pos'];
    		$description = $vars['description'];
    		$query       = $database->update("menu_cat", "pos = '$pos'", "id = '$posid'");
    		header('location: ../admin/index.php?edit=menu&updated=1');
  		}
  		
  		// ==================================================================
  		// Delete a menu category

  		function menusCategoryDelete($vars){
    		global $database;
    		$catid   = $vars['catid'];
    		$menu    = $vars['return'];
    		$mid     = $vars['mid'];
    		$query   = $database->delete("menu_cat", "id = '$catid'");
    		$results = $database->select("SELECT * FROM menu_item  where cat = " . $catid . " ");
    		
    		for ($i = 0; $i < count($results); $i++) {
      		$database->delete("menu_item", "id = " . $results[$i]['id'] . "");
    		} //$i = 0; $i < count($results); $i++
    		header('location: ../admin/index.php?edit=menu&updated=1');
  		}
  		
  		// ==================================================================
  		//First lets add a item to a category

		function menusItemAdd($vars, $files){
    		global $database;
    		$mid         = $vars['mid'];
    		$name        = $vars['name'];
    		$menu        = $vars['menu'];
    		$cat         = $vars['cat'];
	  		$description = $vars['description'];
    		$feature     = $vars['feature'];
    		$price       = serialize($vars['price']);
    		$rid         = $vars['rid'];
    		
    		if ($files['image']['size'] != 0) {
      		$image       = uploadImage($files, '900', '900', '../UserFiles/Image/product_photos/', 'image');
      		$image_thumb = uploadImage($files, '300', '300', '../UserFiles/Image/product_photos/thumbs/', 'image', $image);
    		} //$files['image']['size'] != 0
    		
    		$options = serialize($vars['options']);
    		$type1   = $vars['type1'];
    		
    		$code    = $vars['price'][0];
    		
    		$query   = $database->insert("menu_item", "name, mid, description, price, feature, cat,type1,code,options,image,rid", "'$name', '$mid', '$description', '$price', '$feature', '$cat', '$type1', '$code', '$options', '$image','$rid'");
    		$id      = $database->insertid();
    		header('location: ../admin/index.php?edit=menu&item_id=' . $id . '&function=edit-item&added=1');
  		}
  		
  		// ==================================================================
  		// We would like to modify item to a category

  		function menusItemModify($vars, $files){
    		global $database;
    		$mid         = $vars['cat'];
    		$id          = $vars['id'];
    		$name        = $vars['name'];
	   	$menu        = $vars['menu'];
    		$description = $vars['description'];
    		$feature     = $vars['feature'];
    		$type1       = $vars['type1'];
    		
    		$code        = $vars['price'][0];
    		
    		$price       = serialize($vars['price']);
    		$options     = serialize($vars['options']);

    		$query       = $database->update("menu_item", "name = '$name', feature='$feature', description = '$description', price = '$price', type1 = '$type1', code = '$code', options = '$options'", "id = '$id'");
    		header('location: ../admin/index.php?edit=menu&cat_id=' . $mid . '&function=edit-cat&update=1');
  		}
  		
  		// ==================================================================
  		// Delete a menu item to a category
		
		function menusItemDelete($vars){
    		global $database;
    		$mid    = $vars['mid'];
    		$itemid = $vars['itemid'];
    		$menu   = $vars['return'];
    		$cat    = $vars['return2'];
    		$query  = $database->delete("menu_item", "id = '$itemid'");
    		header('location: ../admin/index.php?edit=menu&cat_id=' . $mid . '&function=edit-cat');
  		}

  		function addOption($vars){
    		global $database;
    		$action['max_toppings'] = $vars['max_toppings'];
    		$action['min_toppings'] = $vars['min_toppings'];
    		$action['name']         = $vars['name'];
    		$action['multi']        = $vars['multi'];
    		$action['pos']          = $vars['pos'];
    		$action['pid']          = $vars['pid'];
    		$action['global']       = '0';
    		$action['rid']          = $vars['rid'];
    		$database->insert_array('options_set', $action);
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function addOptionItem($vars){
    		global $database;
    		$action['name']   = $vars['name'];
    		$action['price']  = $vars['price'];
    		$action['parent'] = $vars['parent'];
    		$database->insert_array('options_items', $action);
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function editOption($vars){
    		global $database;
    		$action['max_toppings'] = $vars['max_toppings'];
    		$action['name']         = $vars['name'];
    		$action['multi']        = $vars['multi'];
    		$action['min_toppings'] = $vars['min_toppings'];
    		$action['pos']          = $vars['pos'];
    		$database->update_array('options_set', $action, 'id= ' . $vars['id'] . '');
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function editOptionItem($vars){
    		global $database;
    		$action['name']  = $vars['name'];
    		$action['price'] = $vars['price'];
    		$database->update_array('options_items', $action, 'id= ' . $vars['id'] . '');
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function deleteOption($vars){
    		global $database;
    		$id    = $vars['id'];
    		$pid   = $vars['pid'];
    		$query = $database->delete("options_set", "id = '$id'");
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function deleteOptionItem($vars){
    		global $database;
    		$id    = $vars['id'];
    		$pid   = $vars['pid'];
    		$query = $database->delete("options_items", "id = '$id'");
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['pid'] . "&function=edit-item");
  		}

  		function copyOptions($vars){
    		error_log("copyoptions: ".var_export($vars, true));
    		global $database;
    		$id      = $vars['id'];
    		$results = $database->select("SELECT * from options_set where pid = '" . $vars['from'] . "'");

    		error_log("copyoptions result: ".var_export($results, true));
    		
    		if ($results != FALSE) {
      		for ($j = 0; $j < count($results); $j++) {
        			$action[$j]['max_toppings'] = $results[$j]['max_toppings'];
        			$action[$j]['name']         = $results[$j]['name'];
        			$action[$j]['multi']        = $results[$j]['multi'];
        			$action[$j]['pid']          = $id;
        			$action[$j]['global']       = '0';
	        		$action[$j]['rid']          = $results[$j]['rid'];
        			$database->insert_array('options_set', $action[$j]);
        			$new_id          = $database->insertid();
        			$results_options = $database->select("SELECT * from options_items where parent = '" . $results[$j]['id'] . "'");
        			
        			for ($i = 0; $i < count($results_options); $i++) {
          			$action_opt[$i]['name']   = $results_options[$i]['name'];
          			$action_opt[$i]['price']  = $results_options[$i]['price'];
          			$action_opt[$i]['parent'] = $new_id;
          			$database->insert_array('options_items', $action_opt[$i]);
        			} //$i = 0; $i < count($results_options); $i++
      		} //$j = 0; $j < count($results); $j++
    		} //$results != FALSE
    		
    		header("Location: ../admin/index.php?edit=menu&item_id=" . $vars['id'] . "&function=edit-item");
  		}

  function menusItemAddPizza($vars, $files){
  		global $database;
  }
  // end class
}
?>
